import {
    LOG_TYPE,
    LOG_TYPE_INDEX
} from './enums';
const UA = navigator.userAgent;

window.log = (type, ...text) => {
    if (type == !!type) type += '';
    if (LOG_TYPE_INDEX.indexOf(+type) == -1 || (text.length == 0 && LOG_TYPE_INDEX.includes(+type))) {
        text = [type, ...text];
        type = 0;
    }
    console[LOG_TYPE[type]]('[log]:', ...text);
}
window.$t = moment

export default {
    env: {
        get: function () {
            return process.env.VUE_APP_PEO_ENV || process.env.NODE_ENV;
        },
        isDev: function () {
            return ['development', 'dev'].includes(this.get());
        },
        isTest: function () {
            return ['test'].includes(this.get())
        },
        isProd: function () {
            return ['devement', 'production', 'prod'].includes(this.get())
        }
    },
    ua: {
        isWx: () => UA.toLowerCase().match(/MicroMessenger/i) == 'micromessenger',
        isAndroid: () => UA.indexOf('Android') > -1 || UA.indexOf('Adr') > -1,
        isIos: () => !!UA.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    },
    /**
     * 设置浏览器默认配置
     * @param {navbar标题} title 
     * @returns 
     */
    setTitle: title => document.title = title,
    scroll2bottom: () => window.scrollTo({
        top: document.body.scrollHeight,
        behavior: 'smooth'
    }),
    isInViewPort: (iv = 90) => {
        let el = document.getElementById('js-bottom');
        let viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        let top = el.getBoundingClientRect() && el.getBoundingClientRect().top;
        return top <= viewPortHeight - iv;
    },
    /**
     * hash模式获取参数值
     * @param {要获取的字段} key 
     * @returns 
     */
    getHashUrlQuery: key => {
        let reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`);
        let arr = location.hash.substr(2).split('?');
        let r = arr.length > 1 ? arr[1].match(reg) : null;
        return r != null ? unescape(r[2]) : null;
    },
    isURL: str_url => {// 验证url
        var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
        + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
        + "|" // 允许IP和DOMAIN（域名）
        + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
        + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
        + "[a-z]{2,6})" // first level domain- .com or .museum
        + "(:[0-9]{1,4})?" // 端口- :80
        + "((/?)|" // a slash isn't required if there is no file name
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        var re = new RegExp(strRegex);
        return re.test(str_url);
      },
    //11位手机号
    _limitPhone(i) {
        var validFormat = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        return validFormat.test(i);
    },
    getQueryName(name) {
        const result = location.search.match(new RegExp(`[\?\&]${name}=([^\&]+)`, 'i'));
        console.log('result',result);
        if (result == null || result.length < 1) {
          return '';
        }
        return result[1];
    },
    /**
     * 获取使用的公众号主体
     * 数据隔离的依据
     * @param {公众号主体} subject 
     * @returns 
     */
    getSubject: function (subject) {
        return this.getHashUrlQuery('subject') || subject.get() || 'mjk'
    },
    /**
     * 对象 --> 拼接字符串
     * @param {query对象} o 
     * @returns name=tom&age=1
     */
    setQueryStringParams: function (o, symbol = '&') {
        let temp = {
                ...o,
                _t: +new Date
            },
            str = '';
        for (let t in temp) {
            str += t + '=' + temp[t] + symbol;
        }
        return str.substr(0, str.length - 1);
    },
    navigateTo: function (u) {
        window.location = u.path + this.setQueryStringParams(u.params)
    },
    redirectTo: function (u) {
        window.replace(u.path + this.setQueryStringParams(u.params))
    },
    /**
     * 下载妙健康app
     */
    download: () => window.location.replace('https://a.app.qq.com/o/simple.jsp?pkgname=cn.funtalk.miao&channel=0002160650432d595942&fromcase=60001'),
    /**
     * 判断数据类型
     * Object.prototype.toString.call(i) === '[object String]'
     * @param {*} i 
     * @returns 
     */
    isString: i => i === i + '',
    isBoolean: i => i === !!i,
    /**
     * 字符串脱敏
     * @param {格式化对象} str
     * @param {+正序坐标} start
     * @param {-倒序坐标} end
     * @returns 
     */
    formatSensitiveStr: (str, start, end) => {
        let len = str.length;
        let first = str.substr(0, start);
        let last = str.substr(end);
        let middle = str.substring(start, len - Math.abs(end)).replace(/[\s\S]/ig, '*');
        return first + middle + last;
    },
    /**
     * 模拟手机号
     * @returns 150****7209
     */
    createMockPhone: () => {
        let prefixArray = ['139', '138', '137', '136', '135', '134', '159', '158', '157', '150', '151', '152', '188', '187', '182', '183', '184', '178', '130', '131', '132', '156', '155', '186', '185', '176', '133', '153', '189', '180', '181', '177'];
        let i = parseInt(10 * Math.random());
        let prefix = prefixArray[i];
        for (let j = 0; j < 8; j++) prefix = prefix + Math.floor(Math.random() * 10);
        return prefix.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
    },
    /**
     * 拼接完整页面路径
     * @returns url
     */
    mergeUrl: path => {
        let {
            origin
        } = window.location;
        return `${origin}/miao_major/index.html#${path}`
    },
    /**
     * @base64 加密方法
     * @encode加密必须为json
     * @decode 解密 
     */
    base64: {
        _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
        encode: function (e) {
            var t = "";
            var n, r, i, s, o, u, a;
            var f = 0;
            e = this._utf8_encode(e);
            while (f < e.length) {
                n = e.charCodeAt(f++);
                r = e.charCodeAt(f++);
                i = e.charCodeAt(f++);
                s = n >> 2;
                o = (n & 3) << 4 | r >> 4;
                u = (r & 15) << 2 | i >> 6;
                a = i & 63;
                if (isNaN(r)) {
                    u = a = 64
                } else if (isNaN(i)) {
                    a = 64
                }
                t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
            }
            return t
        },
        decode: function (e) {
            var t = "";
            var n, r, i;
            var s, o, u, a;
            var f = 0;
            e = e.replace(/[^A-Za-z0-9+/=]/g, "");
            while (f < e.length) {
                s = this._keyStr.indexOf(e.charAt(f++));
                o = this._keyStr.indexOf(e.charAt(f++));
                u = this._keyStr.indexOf(e.charAt(f++));
                a = this._keyStr.indexOf(e.charAt(f++));
                n = s << 2 | o >> 4;
                r = (o & 15) << 4 | u >> 2;
                i = (u & 3) << 6 | a;
                t = t + String.fromCharCode(n);
                if (u != 64) {
                    t = t + String.fromCharCode(r)
                }
                if (a != 64) {
                    t = t + String.fromCharCode(i)
                }
            }
            t = this._utf8_decode(t);
            return t
        },
        _utf8_encode: function (e) {
            e = e.replace(/rn/g, "n");
            var t = "";
            for (var n = 0; n < e.length; n++) {
                var r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r)
                } else if (r > 127 && r < 2048) {
                    t += String.fromCharCode(r >> 6 | 192);
                    t += String.fromCharCode(r & 63 | 128)
                } else {
                    t += String.fromCharCode(r >> 12 | 224);
                    t += String.fromCharCode(r >> 6 & 63 | 128);
                    t += String.fromCharCode(r & 63 | 128)
                }
            }
            return t
        },
        _utf8_decode: function (e) {
            var t = "";
            var n = 0;
            var r = 0,
                c1 = 0,
                c2 = 0,
                c3 = 0;
            while (n < e.length) {
                r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r);
                    n++
                } else if (r > 191 && r < 224) {
                    c2 = e.charCodeAt(n + 1);
                    t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                    n += 2
                } else {
                    c2 = e.charCodeAt(n + 1);
                    c3 = e.charCodeAt(n + 2);
                    t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                    n += 3
                }
            }
            return t
        }
    },
    /**
     * 通栏-状态栏高度
     * sbHeight 传入状态栏高度值
     */
    fniomfov(sbHeight) {
        let self = this;
        let swiSize = {
            swipheight: '',
            swiptop: ''
        };
        let fontSizes = parseFloat(window.getComputedStyle(document.documentElement)["fontSize"]);
        if (fontSizes) {
            let devicenum = 1;
            if (!sbHeight) {
                console.log('no sbHeight')
                self.iomfov = fontSizes * 0.38;
            } else {
                if (self.ua.isIos()) {
                    console.log('ios')
                    if (window.devicePixelRatio == 2 && sbHeight > 129) {
                        console.log('刘海并且dpr=2')
                        devicenum = 3 / 2;
                    }
                    self.iomfov = parseFloat(sbHeight) / devicenum / window.devicePixelRatio;
                } else {
                    console.log('android')
                    self.iomfov = parseFloat(sbHeight) / devicenum;
                }
            }
            swiSize.swipheight = self.iomfov + 1.106667 * fontSizes;
            swiSize.swiptop = self.iomfov + 0.3 * fontSizes;
            console.log('size:' + fontSizes);
            console.log('devicePixelRatio:' + window.devicePixelRatio)
            console.log('iomfov:' + self.iomfov)
            return swiSize
        } else {
            setTimeout(function () {
                self.fniomfov();
            }, 100)
        }
    },
}